<template>
    <div style="font-size:15px;font-weight: 600;margin-left: 60px;">{{ !dataForm.id ? '新增属性组' : '编辑属性组' }}</div>
    <el-form label-width="110px" style="margin-top: 20px;margin-left: -32px;" :model="dataForm" :rules="rules"
        ref="dataFormRef">
        <div style="margin-left: 64px;margin-top: 20px;">
            <el-form-item label="属性组名称" prop="groupName">
                <el-input v-model="dataForm.groupName" placeholder="请输入属性组名称" :maxlength="8" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="属性名称" prop="attrName">
                <div class="model-container">
                    <div v-for="(attr, index) in dataForm.attrClassifyList" :key="index" class="model-item">
                        <input v-model="attr.className" placeholder="请输入属性名称" class="model-input" />
                        <img src="../../assets/images/add.jpg" alt="" @click="addAttrClassify" style="margin-right: 15px;">
                        <img v-if="dataForm.attrClassifyList.length > 1" src="../../assets/images/delete2.jpg" alt="" @click="removeAttrClassify(index)">
                    </div>
                </div>
            </el-form-item>
            <div class="foot">
                <el-button class="quxiao" @click="cancel()">{{ $t("cancel") }}</el-button>
                <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
            </div>
        </div>
    </el-form>
</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus"
import { reactive, ref, toRefs } from "vue";
import { useI18n } from "vue-i18n";
import {useRoute, useRouter} from 'vue-router';
import useView from "@/hooks/useView";


const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const dataForm = reactive({
    id: "",
    groupName: "",
    attrName: "",
    remark: "",
    attrClassifyList: []
});
const route = useRoute();
const id = route.query.id;

const init = () => {

    // 重置表单数据
    if (dataFormRef.value) {
        dataFormRef.value.resetFields();
    }

    // 如果是编辑模式，则获取属性组信息
    if (id) {
        dataForm.id = id.toString();
        baseService.get(`/noc/attrgroup/info/${id}`).then(res => {
            if (res.code === 0 && res.data) {
                dataForm.groupName = res.data.groupName;
                dataForm.attrClassifyList = res.data.attrClassifyList;
            } else {
                ElMessage.error('获取属性组信息失败');
            }
        });
    } else {
        dataForm.groupName = "";
        dataForm.attrName = "";
        dataForm.remark = "";
        dataForm.attrClassifyList = [{  groupId: "", className: ''}];
    }
};

init();

const rules = ref({
    groupName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
    attrName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
});


// 添加新的型号输入框
const addAttrClassify = () => {
    dataForm.attrClassifyList.push({ groupId: id, className: '' });
};

// 删除指定索引的型号输入框
const removeAttrClassify = (index: any) => {
    if (dataForm.attrClassifyList.length <= 1) {
        ElMessage.warning('属性组至少有一个属性');
        return;
    }
    dataForm.attrClassifyList.splice(index, 1);
};

const view = reactive({});

const state = reactive({ ...useView(view), ...toRefs(view) });
const router = useRouter();

const cancel = () => {
    router.push('/program/attribute-list');
    // 关闭当前标签页（需确保useView hook已正确配置）
    state.closeCurrentTab();
};
// 表单提交
const dataFormSubmitHandle = () => {
    // 将models中的name值合并为分号分隔的字符串
    dataForm.attrName = dataForm.attrClassifyList.map(attr => attr.className).join(';');

    dataFormRef.value.validate((valid: boolean) => {
        if (!valid) {
            return false;
        }

        // 检查是否有重复的属性名
        const attrNames = dataForm.attrName.split(';');
        const uniqueNames = new Set(attrNames);
        if (uniqueNames.size !== attrNames.length) {
            ElMessage.error('属性名称不能重复');
            return false;
        }

        // 检查是否有空的属性名
        if (attrNames.some(name => !name.trim())) {
            ElMessage.error('属性名称不能为空');
            return false;
        }

        (!dataForm.id ? baseService.post("/noc/attrgroup/save", dataForm) : baseService.put("/noc/attrgroup/update", dataForm)).then((res) => {
            if (res.code === 0) {
                ElMessage.success({
                    message: t("prompt.success"),
                    duration: 500,
                    onClose: () => {
                        // 关闭当前标签页（需确保useView hook已正确配置）
                        state.closeCurrentTab();

                        router.push('/program/attribute-list').then(() => {
                          router.go(0); // 导航完成后刷新页面
                        });

                    }
                });
            } else {
                ElMessage.error(res.msg || '操作失败');
            }
        });
    });
};


</script>


<style lang="scss" scoped>
.el-input {
    width: 218px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1);
}

.el-select {
    width: 218px;
    height: 32px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(255, 255, 255, 1);
}

.form {
    display: flex;
    justify-content: space-between;
}

.product-detail-upload {
    margin-top: 10px;
}

.label {
    display: inline-block;
    width: 80px;
    margin-right: 10px;
    text-align: right;
}

.upload-box {
    width: 400px;
    border: 2px dashed #ccc;
    border-radius: 6px;
    background-color: #fafafa;
    text-align: center;
    padding: 20px 0;
    cursor: pointer;
}

.upload-box i {
    font-size: 36px;
    color: #409eff;
}

.el-upload__text {
    display: block;
    margin-top: 10px;
    font-size: 14px;
    color: #666;
}

.el-upload__tip {
    margin-top: 5px;
    font-size: 12px;
    color: #999;
}

.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);

}

.foot {
    display: flex;
    justify-content: end;
    position: absolute;
    bottom: 50px;
    right: 50px;

}

.add-button {
    width: 100px;
    height: 32px;
    padding: 10px 20px;
    background-color: rgba(22, 119, 255, 1);
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-bottom: 20px;
}

.add-button:hover {
    background-color: rgba(22, 119, 255, 1);
}


.model-item {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
}

.model-select {
    padding: 8px;
    margin-right: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.model-input {
    padding: 8px;
    margin-right: 10px;
    border-radius: 5px;
    width: 218px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(199, 199, 199, 1);
}

.model-input:focus {
    border: 0;
    /* 获得焦点时边框颜色改为蓝色 */
    background: rgba(240, 245, 255, 1);
    color: rgba(22, 119, 255, 1);
    outline: none;
    /* 去除默认的焦点轮廓 */
}

.remove-button {
    padding: 8px 12px;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.quxiao {
    border-radius: 5px;
    background: rgba(239, 244, 255, 1);
    color: rgba(22, 119, 255, 1);
    border: 1px solid rgba(22, 119, 255, 1);
}

.uploaded-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
}
</style>
